package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.device.dao.DeviceWorkshopDao;
import com.wing.device.model.response.DeviceWorkshopVO;
import com.wing.enumeration.DispatchWorkStatusEnum;
import com.wing.product.dao.ProductDispatchWorkDao;
import com.wing.product.dao.ProductDispatchWorkDetailDao;
import com.wing.product.model.entity.ProductDispatchWork;
import com.wing.product.model.entity.ProductDispatchWorkDetail;
import com.wing.product.model.request.ProductDispatchWorkInfoDetailForm;
import com.wing.product.model.request.ProductDispatchWorkInfoForm;
import com.wing.product.model.response.ProductDispatchWorkDetailVO;
import com.wing.product.model.response.ProductDispatchWorkInfoEditVO;
import com.wing.product.model.response.ProductDispatchWorkUserVO;
import com.wing.product.model.response.ProductDispatchWorkVO;
import com.wing.res.dao.ResWorkStationDao;
import com.wing.res.model.response.ResWorkStationSearchVo;
import com.wing.sell.model.entity.OrderPro;
import com.wing.system.dao.DingTalkAttendanceDao;
import com.wing.system.dao.DingTalkAttendanceGroupDao;
import com.wing.system.dao.DingTalkAttendanceGroupSettingTimesDao;
import com.wing.system.model.entity.DingTalkAttendanceGroup;
import com.wing.system.model.response.DingTalkAttendanceGroupSettingTimesVO;
import com.wing.system.model.response.DingTalkAttendanceGroupUseVo;
import com.wing.system.model.response.DingTalkAttendanceVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 派工
 *
 */
@Service
@Slf4j
public class ProductDispatchWorkServiceImpl extends ServiceImpl<ProductDispatchWorkDao, ProductDispatchWork> implements ProductDispatchWorkService {


    @Autowired
    DeviceWorkshopDao deviceWorkshopDao;

    @Autowired
    DingTalkAttendanceGroupDao dingTalkAttendanceGroupDao;

    @Autowired
    DingTalkAttendanceGroupSettingTimesDao dingTalkAttendanceGroupSettingTimesDao;

    @Autowired
    ResWorkStationDao resWorkStationDao;

    @Autowired
    DingTalkAttendanceDao dingTalkAttendanceDao;

    @Autowired
    ProductDispatchWorkDetailDao productDispatchWorkDetailDao;


    // 模拟每日序列号，实际应用中应该从持久化存储中读取和保存这个值
    private static int dailyCounter = 0; // 这里仅用于演示

    @Override
    public List<DeviceWorkshopVO> getDeviceWorkshopList() {
        return deviceWorkshopDao.getDeviceWorkshopList();
    }

    @Override
    public List<DingTalkAttendanceGroupUseVo> selAllGroupList() {
        return dingTalkAttendanceGroupDao.selAllGroupList();
    }




    @Override
    public Page<ProductDispatchWorkVO> checkDeviceWorkToAttendanceTime(String workshopId, String groupId) {

        // 查询车间对应的工位相关信息
        List<ResWorkStationSearchVo> workshopListInfo = resWorkStationDao.getWorkshopListInfo(workshopId);

        // 查询对应考勤组上下班时间
        List<DingTalkAttendanceGroupSettingTimesVO> dingTalkAttendanceGroupSettingTimesVOS = dingTalkAttendanceGroupSettingTimesDao.selDingTalkAttendanceGroupSettingTimes(groupId);

        // 两个集合的结果数据
        List<ProductDispatchWorkVO> productDispatchWorkVOList = new ArrayList<>();

        if (dingTalkAttendanceGroupSettingTimesVOS.isEmpty()) {
            // 如果 dingTalkAttendanceGroupSettingTimesVOS 为空，则只处理 workshopListInfo 的信息
            for (ResWorkStationSearchVo resWorkStationSearchVo : workshopListInfo) {
                ProductDispatchWorkVO productDispatchWorkVO = new ProductDispatchWorkVO();

                productDispatchWorkVO.setGongWeiId(resWorkStationSearchVo.getId());
                productDispatchWorkVO.setName(resWorkStationSearchVo.getName());
                productDispatchWorkVO.setCode(resWorkStationSearchVo.getCode());
                productDispatchWorkVO.setNature(resWorkStationSearchVo.getNature());
                productDispatchWorkVO.setNatureName(resWorkStationSearchVo.getNatureName());
                productDispatchWorkVO.setPostId(resWorkStationSearchVo.getPostId());
                productDispatchWorkVO.setPostName(resWorkStationSearchVo.getPostName());
                productDispatchWorkVO.setWorkshopId(resWorkStationSearchVo.getWorkshopId());
                productDispatchWorkVO.setWorkshopName(resWorkStationSearchVo.getWorkshopName());
                productDispatchWorkVO.setDepartmentId(resWorkStationSearchVo.getDepartmentId());
                productDispatchWorkVO.setDepartmentName(resWorkStationSearchVo.getDepartmentName());

                // 设置默认值或留空对于考勤组相关的字段
                productDispatchWorkVO.setClassId(null);
                productDispatchWorkVO.setClassName("");
                productDispatchWorkVO.setWorkBeginTime("");
                productDispatchWorkVO.setWorkEndTime("");
                productDispatchWorkVO.setGroupId(null);
                productDispatchWorkVO.setGroupName("");

                productDispatchWorkVOList.add(productDispatchWorkVO);
            }
        } else {
            // 如果 dingTalkAttendanceGroupSettingTimesVOS 不为空，则使用现有的逻辑
            for (ResWorkStationSearchVo resWorkStationSearchVo : workshopListInfo) {
                Long workshopId2 = resWorkStationSearchVo.getWorkshopId();
                String workshopName = resWorkStationSearchVo.getWorkshopName();
                Long departmentId = resWorkStationSearchVo.getDepartmentId();
                String departmentName = resWorkStationSearchVo.getDepartmentName();
                String name = resWorkStationSearchVo.getName();
                Long id = resWorkStationSearchVo.getId();
                String code = resWorkStationSearchVo.getCode();
                String natureName = resWorkStationSearchVo.getNatureName();
                Long nature = resWorkStationSearchVo.getNature();
                String postName = resWorkStationSearchVo.getPostName();
                Long postId = resWorkStationSearchVo.getPostId();

                for (DingTalkAttendanceGroupSettingTimesVO dingTalkAttendanceGroupSettingTimesVO : dingTalkAttendanceGroupSettingTimesVOS) {
                    String className = dingTalkAttendanceGroupSettingTimesVO.getClassName();
                    Long classId = dingTalkAttendanceGroupSettingTimesVO.getClassId();
                    String workBeginTime = dingTalkAttendanceGroupSettingTimesVO.getWorkBeginTime();
                    String workEndTime = dingTalkAttendanceGroupSettingTimesVO.getWorkEndTime();
                    Long groupId1 = dingTalkAttendanceGroupSettingTimesVO.getGroupId();
                    String groupName = dingTalkAttendanceGroupSettingTimesVO.getGroupName();

                    ProductDispatchWorkVO productDispatchWorkVO = new ProductDispatchWorkVO();

                    productDispatchWorkVO.setGongWeiId(id);
                    productDispatchWorkVO.setName(name);
                    productDispatchWorkVO.setCode(code);
                    productDispatchWorkVO.setNature(nature);
                    productDispatchWorkVO.setNatureName(natureName);
                    productDispatchWorkVO.setPostId(postId);
                    productDispatchWorkVO.setPostName(postName);
                    productDispatchWorkVO.setWorkshopId(workshopId2);
                    productDispatchWorkVO.setWorkshopName(workshopName);
                    productDispatchWorkVO.setDepartmentId(departmentId);
                    productDispatchWorkVO.setDepartmentName(departmentName);

                    productDispatchWorkVO.setClassId(classId);
                    productDispatchWorkVO.setClassName(className);
                    productDispatchWorkVO.setWorkBeginTime(workBeginTime);
                    productDispatchWorkVO.setWorkEndTime(workEndTime);
                    productDispatchWorkVO.setGroupId(groupId1);
                    productDispatchWorkVO.setGroupName(groupName);

                    //需要关联查看以及有哪些用户关联上了 责任人相关信息

                    productDispatchWorkVOList.add(productDispatchWorkVO);
                }
            }
        }
        Page<ProductDispatchWorkVO> pg=new Page<>();
        pg.setRecords(productDispatchWorkVOList);

        //把责任岗位对应的用户都拿出来

        return pg;
   }


    @Override
    public List<ProductDispatchWorkUserVO> getDispatchWorkUserInfo(String postId, String groupId, String dispatchWorkDate) {
        if(StringUtils.isEmpty(dispatchWorkDate)){
            return new ArrayList<>();
        }
        dispatchWorkDate = dispatchWorkDate.substring(0, 10);
        //查询对应日期  考勤组有哪些人需要工作
        List<DingTalkAttendanceVO> dingTalkAttendanceVOS = dingTalkAttendanceDao.selDingTalkAttendanceByDate(groupId, dispatchWorkDate);
        //查询岗位下面对应的用户
        List<ProductDispatchWorkUserVO> productDispatchWorkUserVOS = baseMapper.selPostUserList(postId);
        // 找出交集的数据
        List<DingTalkAttendanceVO> intersectionList = findIntersection(dingTalkAttendanceVOS, productDispatchWorkUserVOS);

        //组装返回数据
        List<ProductDispatchWorkUserVO> productDispatchWorkUserVOList=new ArrayList<>();
        // 输出结果或进一步处理
        for (DingTalkAttendanceVO vo : intersectionList) {
            ProductDispatchWorkUserVO productDispatchWorkUserVO=new ProductDispatchWorkUserVO();
            productDispatchWorkUserVO.setDingUserId(vo.getDingUserId());
            productDispatchWorkUserVO.setUserId(vo.getUserid());
            productDispatchWorkUserVO.setNickname(vo.getName());
            productDispatchWorkUserVOList.add(productDispatchWorkUserVO);
        }
        return productDispatchWorkUserVOList;
    }

    @Override
    public Page<ProductDispatchWorkVO> selDispatchListInfo(Page page, Map<String, Object> params) {
        List<ProductDispatchWorkVO> list = baseMapper.selDispatchListInfo(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional
    public JsonResult saveDispatchWorkInfo(ProductDispatchWorkInfoForm productDispatchWorkInfoForm) {
        if(productDispatchWorkInfoForm.getDispatchWorkInfoDetailFormList().size()<=0){
            return JsonResult.fail("请添加工位信息");
        }

        if(productDispatchWorkInfoForm.getId()!=null){
            //表示是修改  先把旧纪录删掉 在重新给加入进去 todo 界面无修改功能 先写上简单逻辑操作
            baseMapper.deleteById(productDispatchWorkInfoForm.getId());
            LambdaQueryWrapper<ProductDispatchWorkDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductDispatchWorkDetail::getDispatchWorkId, productDispatchWorkInfoForm.getId());
            productDispatchWorkDetailDao.delete(wrapper);
        }


        ProductDispatchWork productDispatchWork=new ProductDispatchWork();

        BeanUtil.copyProperties(productDispatchWorkInfoForm, productDispatchWork);
        productDispatchWork.setDeviceWorkshopId(productDispatchWorkInfoForm.getDeviceWorkshopId());
        productDispatchWork.setDispatchWorkNumber(generateFormattedCode());
        productDispatchWork.setCreatorName(JwtUtils.getLoginUsername());
        productDispatchWork.setCreator(JwtUtils.getLoginUserId());
        productDispatchWork.setCreateTime(LocalDateTime.now());

        productDispatchWork.setDispatchWorkStatus(DispatchWorkStatusEnum.AUDIT_PASS.getDescription());
        productDispatchWork.setDispatchWorkStatusCode(DispatchWorkStatusEnum.AUDIT_PASS.getCode());

        baseMapper.insert(productDispatchWork);


        List<ProductDispatchWorkInfoDetailForm> dispatchWorkInfoDetailFormList = productDispatchWorkInfoForm.getDispatchWorkInfoDetailFormList();
        for (ProductDispatchWorkInfoDetailForm productDispatchWorkInfoDetailForm : dispatchWorkInfoDetailFormList) {
            ProductDispatchWorkDetail productDispatchWorkDetail=new ProductDispatchWorkDetail();
            productDispatchWorkDetail.setDispatchWorkNumber(productDispatchWork.getDispatchWorkNumber());
            productDispatchWorkDetail.setDispatchWorkId(productDispatchWork.getId());

            BeanUtil.copyProperties(productDispatchWorkInfoDetailForm, productDispatchWorkDetail);



            productDispatchWorkDetail.setAttendanceGroupName(productDispatchWork.getAttendanceGroupName());
            productDispatchWorkDetail.setAttendanceGroupId(productDispatchWork.getAttendanceGroupId());
            productDispatchWorkDetail.setWorkStationName(productDispatchWorkInfoDetailForm.getName());
            productDispatchWorkDetail.setWorkStationCode(productDispatchWorkInfoDetailForm.getCode());
            productDispatchWorkDetail.setWorkStationNature(productDispatchWorkInfoDetailForm.getNatureName());
            productDispatchWorkDetail.setWorkStationNatureId(productDispatchWorkInfoDetailForm.getNature());
            productDispatchWorkDetail.setWorkStationPostName(productDispatchWorkInfoDetailForm.getPostName());
            productDispatchWorkDetail.setWorkStationPostId(productDispatchWorkInfoDetailForm.getPostId());
            productDispatchWorkDetail.setAttendanceBanId(productDispatchWorkInfoDetailForm.getClassId());
            productDispatchWorkDetail.setAttendanceBanName(productDispatchWorkInfoDetailForm.getClassName());


            productDispatchWorkDetail.setCreatorName(JwtUtils.getLoginUsername());
            productDispatchWorkDetail.setCreator(JwtUtils.getLoginUserId());
            productDispatchWorkDetail.setCreateTime(LocalDateTime.now());

            productDispatchWorkDetailDao.insert(productDispatchWorkDetail);

        }
        return JsonResult.success();
    }

    @Override
    public HashMap<String, Object> getTopDispatchCount(String workshopId, String groupId) {
        HashMap<String, Object> topHashMap=new HashMap<>();
        topHashMap.put("banCount",0);
        topHashMap.put("workStationPostCount",0);
        topHashMap.put("dispatchWorkCount",0);

        HashMap<String, Object>  workshopTopCountMap= resWorkStationDao.getWorkshopTopCount(workshopId);
        if(workshopTopCountMap!=null && workshopTopCountMap.size()>0){
            topHashMap.put("dispatchWorkCount",workshopTopCountMap.get("res_work_station_count"));
            topHashMap.put("workStationPostCount",workshopTopCountMap.get("post_count"));
        }

        if(StringUtils.isNotEmpty(groupId)){
            DingTalkAttendanceGroup talkAttendanceGroup = dingTalkAttendanceGroupDao.selGroupInfo(Long.valueOf(groupId));
            JSONArray classesArray = JSON.parseArray(talkAttendanceGroup.getClassesList());
            Integer banCiCount= classesArray.size();
            topHashMap.put("banCount",banCiCount);
       }
      return topHashMap;
    }

    @Override
    public ProductDispatchWorkInfoEditVO getDispatchWorkInfoEditList(String dispatchWorkNumber,Long id) {

        ProductDispatchWorkInfoEditVO dispatchWorkInfoEditVO=new ProductDispatchWorkInfoEditVO();
        ProductDispatchWork productDispatchWork = baseMapper.selectById(id);
        if(productDispatchWork!=null){
            BeanUtil.copyProperties(productDispatchWork, dispatchWorkInfoEditVO);

            List<ProductDispatchWorkVO> productDispatchWorkUserVOList=new ArrayList<>();

            List<ProductDispatchWorkDetailVO> productDispatchWorkDetailVOS = productDispatchWorkDetailDao.selDispatchDetailListInfo(productDispatchWork.getId(), dispatchWorkNumber);
            for (ProductDispatchWorkDetailVO productDispatchWorkDetailVO : productDispatchWorkDetailVOS) {
                ProductDispatchWorkVO productDispatchWorkVO = new ProductDispatchWorkVO();

                productDispatchWorkVO.setGongWeiId(id);
                productDispatchWorkVO.setName(productDispatchWorkDetailVO.getWorkStationName());
                productDispatchWorkVO.setCode(productDispatchWorkDetailVO.getWorkStationCode());
                productDispatchWorkVO.setNature(productDispatchWorkDetailVO.getWorkStationNatureId());
                productDispatchWorkVO.setNatureName(productDispatchWorkDetailVO.getWorkStationNature());
                productDispatchWorkVO.setPostId(productDispatchWorkDetailVO.getWorkStationPostId());
                productDispatchWorkVO.setPostName(productDispatchWorkDetailVO.getWorkStationPostName());
                productDispatchWorkVO.setWorkshopId(Long.valueOf(productDispatchWork.getDeviceWorkshopId()));
                productDispatchWorkVO.setWorkshopName(productDispatchWork.getDeviceWorkshopName());


                productDispatchWorkVO.setClassId(productDispatchWorkDetailVO.getAttendanceBanId());
                productDispatchWorkVO.setClassName(productDispatchWorkDetailVO.getAttendanceBanName());
                productDispatchWorkVO.setWorkBeginTime(productDispatchWorkDetailVO.getWorkBeginTime());
                productDispatchWorkVO.setWorkEndTime(productDispatchWorkDetailVO.getWorkEndTime());
                productDispatchWorkVO.setGroupId(productDispatchWorkDetailVO.getAttendanceGroupId());
                productDispatchWorkVO.setGroupName(productDispatchWorkDetailVO.getAttendanceGroupName());

                productDispatchWorkVO.setDutyUserId(productDispatchWorkDetailVO.getDutyUserId());
                productDispatchWorkVO.setDutyUserName(productDispatchWorkDetailVO.getDutyUserName());

                productDispatchWorkUserVOList.add(productDispatchWorkVO);
            }

            dispatchWorkInfoEditVO.setProductDispatchWorkUserVOList(productDispatchWorkUserVOList);
        }


        return dispatchWorkInfoEditVO;
    }


    /**
     * 生成指定格式的编码
     * @return 返回格式化的编码字符串
     */
    public static String generateFormattedCode() {
        LocalDate today = LocalDate.now(); // 获取当前日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); // 定义日期格式
        String datePart = today.format(formatter); // 格式化日期

        // 增加每日计数器并格式化为三位数
        dailyCounter++;
        String counterPart = String.format("%03d", dailyCounter);

        return "BG" + datePart + counterPart;
    }



    //查询交集信息 两个用户集合里面
    private static List<DingTalkAttendanceVO> findIntersection(List<DingTalkAttendanceVO> attendanceVOS, List<ProductDispatchWorkUserVO> userVOS) {
        // 将userVOS中的userId收集到一个集合中以便快速查找
        List<String> userIdsFromUsers = userVOS.stream().map(ProductDispatchWorkUserVO::getDingUserId).collect(Collectors.toList());

        // 使用Stream API过滤attendanceVOS，保留那些在userIdsFromUsers中存在的记录
        return attendanceVOS.stream()
                .filter(vo -> userIdsFromUsers.contains(vo.getDingUserId()))
                .collect(Collectors.toList());
    }

}
